import { createApp, type DirectiveBinding, type ObjectDirective } from 'vue';
import ContextMenu from '@/components/ContextMenu/index.vue';


console.log(ContextMenu);


interface ContextMenuOptions {
  items: { text: string; action: () => void }[];
}

const contextMenuDirective: ObjectDirective<any, ContextMenuOptions> = {
  mounted(el, binding) {
    const { items } = binding.value ?? {};
    const container = document.createElement('div');
    container.style.position = 'fixed';
    container.style.width = '100px';
    container.style.height = '100%';
    // container.style.width = 'absolute';
    container.style.zIndex = '99999';

    const app = createApp(ContextMenu, { items });
    const componentInstance = app.mount(container);

    el.addEventListener('contextmenu', (event: any) => {
      event.preventDefault();
      document.body.appendChild(container);
      // el.appendChild(container);
      container.style.display = 'block';

      // 强制重绘，确保元素在下一帧被添加到文档流中
      void container.offsetHeight;
      void container.offsetWidth;

      console.log();
      

      // 获取菜单的尺寸
      const menuHeight = container.children[0].clientHeight;
      const menuWidth = container.children[0].clientWidth;

      // 获取鼠标的位置
      const mouseX = event.pageX;
      const mouseY = event.pageY;

      console.log(menuHeight, menuWidth, mouseX, mouseY, container);
      

      // 获取浏览器窗口的尺寸
      const windowWidth = window.innerWidth;
      const windowHeight = window.innerHeight;

      // 调整菜单的位置，确保不会超出窗口边缘
      let x = mouseX;
      let y = mouseY;

      if (mouseX + menuWidth > windowWidth) {
        x = mouseX - menuWidth;
      }

      if (mouseY + menuHeight > windowHeight) {
        y = mouseY - menuHeight;
      }

      componentInstance.$nextTick(() => {
        componentInstance.setPosition(x, y);
        componentInstance.open();
      });
    });

    window.addEventListener('click', () => {
      container.style.display = 'none';
    });
  },
};

export default contextMenuDirective;